from rest_framework import serializers

from .models import User


class UserSerializer(serializers.HyperlinkedModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name='api:user-detail')

    class Meta:
        model = User
        fields = ['id', 'url', 'username', 'password', 'last_login', 'date_joined']
        read_only_fields = ['last_login', 'date_joined']
        # 设置密码只写
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def create(self, validated_data):
        user = User(
            username=validated_data['username'],
        )
        user.set_password(validated_data['password'])
        user.save()
        return user


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        exclude = ['groups', 'is_active', 'is_staff', 'is_superuser', 'user_permissions']
        read_only_fields = ['last_login', 'date_joined']
